import type { Tab } from '#/browser/entities/tab.entity'
import type { BaseWindow } from 'electron'
/**
 * @file 单独窗口管理器
 * @description 维护已打开的单独窗口列表，实时同步到 openWindows
 * @author 黄敏
 * @since 2025-08-26 15:22
 */
import { SeparateController } from '#/browser/controllers/separate.controller'
import { TypedEventEmitter } from '#/utils/events'

type Events = {
  // 打开中的窗口列表变化
  'open-windows:change': (openWindows: number[]) => void
}

export class SeparateWindowManager extends TypedEventEmitter<Events> {
  private readonly windows: SeparateController[] = []
  electronWindow: BaseWindow
  // 已经打开的单独窗口（记录 tabId）
  private openWindows: number[] = []

  getOpenWindows() {
    return this.openWindows
  }

  constructor(electronWindow: BaseWindow) {
    super()
    this.electronWindow = electronWindow
  }

  private addOpenWindow(id: number) {
    if (!this.openWindows.includes(id)) {
      this.openWindows.push(id)
      this.emit('open-windows:change', this.openWindows)
    }
  }

  private removeOpenWindow(id: number) {
    const i = this.openWindows.indexOf(id)
    if (i !== -1) {
      this.openWindows.splice(i, 1)
      this.emit('open-windows:change', this.openWindows)
    }
  }

  openWindow(tab: Tab, type: F2.tab.ControllerType) {
    const existed = this.windows.find(win => win.data.id === tab.data.id)
    if (existed) {
      // 交由窗口自身的 show/restore 事件驱动 openWindows 维护
      existed.open()
      return
    }

    const separateWindow = new SeparateController(tab, this.electronWindow, type)

    // 监听关闭，实时移除记录
    separateWindow.on('closed', () => {
      const idx = this.windows.indexOf(separateWindow)
      if (idx !== -1) this.windows.splice(idx, 1)
      this.removeOpenWindow(separateWindow.data.id)
    })

    separateWindow.on('shown', () => this.addOpenWindow(separateWindow.data.id))
    separateWindow.on('hidden', () => this.removeOpenWindow(separateWindow.data.id))

    this.windows.push(separateWindow)
    // 新建即记录
    this.addOpenWindow(separateWindow.data.id)
    separateWindow.open()
  }

  // 判断id是否存在
  isWindowOpen(tabId: number) {
    return this.windows.some(win => win.data.id === tabId)
  }

  // 获取窗口
  getWindow(tabId: number) {
    return this.windows.find(win => win.data.id === tabId)
  }

  /**
   * 通过tabId 获取窗口
   * @param tabId - 标签页ID
   * @returns 窗口实例
   * */
  getWindowByTabId(tabId: number) {
    return this.windows.find(win => win.tabId === tabId)
  }
}
